<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\QrCodeController;
use App\Http\Controllers\ZipFileDownloadController;
use App\Models\AnswerActivity;
use App\Models\AnswerActivityBaseUnit;
use App\Models\AnswerActivityUnit;
use App\Validate\AnswerActivityUnitValidate;
use Exception;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * 活动单位管理
 */
class AnswerActivityUnitController extends CommonController
{

    public $model = null;
    public $validate = null;

    public function __construct()
    {
        parent::__construct();

        $this->model = new AnswerActivityUnit();
        $this->validate = new AnswerActivityUnitValidate();
    }



    /**
     * 获取单位性质
     */
    public function getNatureName()
    {
        $data = $this->model->getNatureName();
        $config_node = config('other.activity_unit_nature');

        $new_data = [];
        $i = 0;
        foreach ($data as $key => $val) {
            if (in_array($key, $config_node)) {
                $new_data[$i]['id'] = $key;
                $new_data[$i]['name'] = $val;
                $i++;
            }
        }

        if ($new_data) {
            return $this->returnApi(200, "获取成功", true, $new_data);
        }
        return $this->returnApi(203, "暂无数据");
    }


    /**
     * 列表(用于下拉框选择)
     * @param act_id 活动id
     */
    public function filterList()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('filter_list')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        //判断是否是单位联盟活动
        $isAllowAddUnit = $this->model->isAllowAddUnit($this->request->act_id);
        if ($isAllowAddUnit !== true) {
            return $this->returnApi(202, $isAllowAddUnit);
        }

        $condition[] = ['is_del', '=', 1];
        $condition[] = ['act_id', '=', $this->request->act_id];

        return $this->model->getFilterList(['id', 'act_id', 'name', 'img', 'nature'], $condition);
    }

    /**
     * 列表
     * @param act_id int 活动id
     * @param area_id int 区域id
     * @param page int 当前页
     * @param limit int 分页大小
     * @param nature int 单位性质   1 图书馆  2 文化馆  3 博物馆
     * @param start_time datetime 创建时间范围搜索(开始)
     * @param end_time datetime 创建时间范围搜索(结束)
     * @param keywords string 搜索关键词(类型名称)
     */
    public function lists()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('list')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $page = $this->request->page ? intval($this->request->page) : 1;
        $limit = $this->request->limit ? intval($this->request->limit) : 10;
        $start_time = $this->request->start_time;
        $end_time = $this->request->end_time;
        $nature = $this->request->nature;
        $keywords = $this->request->keywords;
        $act_id = $this->request->act_id;
        $area_id = $this->request->area_id;

        //判断是否是单位联盟活动
        $isAllowAddUnit = $this->model->isAllowAddUnit($this->request->act_id);
        if ($isAllowAddUnit !== true) {
            return $this->returnApi(202, $isAllowAddUnit);
        }

        $res = $this->model->lists(null, $act_id, $keywords, $area_id, $nature, null, $start_time, $end_time, null, null, $limit);

        if ($res['total'] == 0 || !$res['data']) {
            return $this->returnApi(203, "暂无数据");
        }

        foreach ($res['data'] as $key => $val) {
            $res['data'][$key]['intro'] = strip_tags($val['intro']);
            $res['data'][$key]['area_name'] = !empty($val['con_area']['name']) ?  $val['con_area']['name'] : '';
            $res['data'][$key]['nature_name'] = $this->model->getNatureName($val['nature']);
            $res['data'][$key][$this->list_index_key] = $this->addSerialNumberOne($key, $page, $limit);

            unset($res['data'][$key]['con_area']);
        }

        return $this->returnApi(200, "查询成功", true, $res);
    }

    /**
     * 详情
     * @param id int 类型id
     */
    public function detail()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('detail')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $res = $this->model->detail($this->request->id);

        if (!$res) {
            return $this->returnApi(201, "参数传递错误");
        }

        return $this->returnApi(200, "获取成功", true, $res->toArray());
    }

    /**
     * 新增
     * @param act_id int活动id
     * @param area_id int区域id  区域联盟必传
     * @param nature int单位性质   1 图书馆  2 文化馆  3 博物馆
     * @param name string 名称   最多 3个字符
     * @param img string 图片
     * @param intro string 简介
     * @param tel string 联系电话
     * @param contacts string 联系人
     * @param words string 单位赠言，最多50字
     * @param province string 省    选填
     * @param city string 市           选填
     * @param district string 区(县)      选填
     * @param address string 详细地址      选填
     * @param is_change_base_data string 是否更新到基础数据库  1是 2否（默认）
     */
    public function add()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('add')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $limitWords = $this->model->limitWords($this->request->words);
        if ($limitWords !== true) {
            return $this->returnApi(202, $limitWords);
        }

        //判断是否是单位联盟活动
        $isAllowAddUnit = $this->model->isAllowAddUnit($this->request->act_id);
        if ($isAllowAddUnit !== true) {
            return $this->returnApi(202, $isAllowAddUnit);
        }
        //是否必传区域id
        $node = AnswerActivity::where('id', $this->request->act_id)->value('node');
        if ($node == 3 && empty($this->request->area_id)) {
            return $this->returnApi(202, '此活动为区域联盟活动，请选择所属区域');
        }

        $condition[] = ['act_id', '=', $this->request->act_id];

        $is_exists = $this->model->nameIsExists($this->request->name, 'name', null, 1, $condition);
        if ($is_exists) {
            return $this->returnApi(202, "此名称已存在");
        }
        $data = $this->request->all();
        $data['letter'] = get_first_charter($this->request->name);
        if (empty($data['img'])) {
            unset($data['img']); //使用默认图
        }
        if ($node != 3) {
            $data['area_id'] = 0;
        }

        //生成二维码
        $qrCodeObj = new QrCodeController();
        $qr_code = $qrCodeObj->getQrCode('answer_activity_unit');
        if ($qr_code === false) {
            Log::error("答题活动单位二维码生成失败,请手动生成");
            return $this->returnApi(200, "新增成功,二维码生成失败", true);
        }
        $qr_data = $this->getDomainName() . '/' . config('other.project_name') . 'wx/pGames/gameLoading/index?from=readshare_activity&token=' . $qr_code; //渝中区二维码的链接  扫码跳转渝中区二维码

        $qr_url = $qrCodeObj->setQr($qr_data, true, 360, 1);
        $data['qr_code'] = $qr_code;
        $data['qr_url'] = $qr_url;


        /*生成经纬度*/
        if (!empty($this->request->province) && !empty($this->request->city) && !empty($this->request->district) && !empty($this->request->address)) {
            $map = $this->getLonLatByAddress($this->request->province . $this->request->city . $this->request->district . $this->request->address);
            if (is_string($map)) {
                return $this->returnApi(202, $map);
            }

            $data['lon'] = $map['lon'];
            $data['lat'] = $map['lat'];
        } else {
            $data['lon'] = null;
            $data['lat'] = null;
        }
        unset($data['is_change_base_data']);
        $res = $this->model->add($data);

        //更新到基础数据库
        if ($this->request->is_change_base_data == 1) {
            $answerActivityBaseUnitModel = new AnswerActivityBaseUnit();
            $answerActivityBaseUnitModel->changeBaseUnit($data);
        }

        if (!$res) {
            return $this->returnApi(202, "新增失败");
        }
        return $this->returnApi(200, "新增成功", true);
    }

    /**
     * 修改
     * @param id int 单位id
     * @param area_id int区域id  区域联盟必传
     * @param nature int单位性质   1 图书馆  2 文化馆  3 博物馆
     * @param name string 名称   最多 3个字符
     * @param img string 图片
     * @param intro string 简介
     * @param tel string 联系电话
     * @param contacts string 联系人
     * @param words string 单位赠言，最多50字
     * @param province string 省    选填
     * @param city string 市           选填
     * @param district string 区(县)      选填
     * @param address string 详细地址      选填
     * @param is_change_base_data string 是否更新到基础数据库  1是 2否（默认）
     */
    public function change()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('change')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $limitWords = $this->model->limitWords($this->request->words);
        if ($limitWords !== true) {
            return $this->returnApi(202, $limitWords);
        }

        $result = $this->model->where('id', $this->request->id)->first();
        if (empty($result)) {
            return $this->returnApi(201, "参数传递错误");
        }

        //判断是否是单位联盟活动
        $isAllowAddUnit = $this->model->isAllowAddUnit($result->act_id);
        if ($isAllowAddUnit !== true) {
            return $this->returnApi(202, $isAllowAddUnit);
        }
        //是否必传区域id
        $node = AnswerActivity::where('id', $result->act_id)->value('node');
        if ($node == 3 && empty($this->request->area_id)) {
            return $this->returnApi(202, '此活动为区域联盟活动，请选择所属区域');
        }

        $condition[] = ['act_id', '=', $result->act_id];
        $is_exists = $this->model->nameIsExists($this->request->name, 'name', $this->request->id, 1, $condition);
        if ($is_exists) {
            return $this->returnApi(202, "此名称已存在");
        }

        $data = $this->request->all();
        $data['img'] = $data['img'] ? $data['img'] : 'default/default_readshare_unit.png';
        $data['letter'] = get_first_charter($this->request->name);
        if ($node != 3) {
            $data['area_id'] = 0;
        }
        /*生成经纬度*/
        if (
            !empty($this->request->province) && !empty($this->request->city) && !empty($this->request->district) && !empty($this->request->address)
            && $this->request->province . $this->request->city . $this->request->district . $this->request->address != $result->province . $result->city . $result->district . $result->address
        ) {
            $map = $this->getLonLatByAddress($this->request->province . $this->request->city . $this->request->district . $this->request->address);
            if (is_string($map)) {
                return $this->returnApi(202, $map);
            }
            $data['lon'] = $map['lon'];
            $data['lat'] = $map['lat'];
        } else {
            $data['lon'] = null;
            $data['lat'] = null;
        }

        if (empty($result['qr_url'])) {
            //生成二维码
            if (empty($result['qr_code'])) {
                $qrCodeObj = new QrCodeController();
                $qr_code = $qrCodeObj->getQrCode('answer_activity_unit');
                if ($qr_code === false) {
                    Log::error("答题活动单位二维码生成失败,请手动生成");
                    return $this->returnApi(200, "新增成功,二维码生成失败", true);
                }
            } else {
                $qr_code = $result['qr_code'];
            }
            $qr_data = $this->getDomainName() . '/' . config('other.project_name') . 'wx/pGames/gameLoading/index?from=readshare_activity&token=' . $qr_code; //渝中区二维码的链接  扫码跳转渝中区二维码
            $qr_url = $qrCodeObj->setQr($qr_data, true, 360, 1);
            $data['qr_code'] = $qr_code;
            $data['qr_url'] = $qr_url;
        }
        unset($data['is_change_base_data']);
        $res = $this->model->change($data);

        //更新到基础数据库
        if ($this->request->is_change_base_data == 1) {
            $answerActivityBaseUnitModel = new AnswerActivityBaseUnit();
            $answerActivityBaseUnitModel->changeBaseUnit($data);
        }

        if (!$res) {
            return $this->returnApi(202, "修改失败");
        }
        return $this->returnApi(200, "修改成功", true);
    }

    /**
     * 删除
     * @param id int 类型id
     */
    public function del()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('del')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $res = $this->model->del($this->request->id);

        if ($res === true) {
            return $this->returnApi(200, "删除成功", true);
        }
        return $this->returnApi(202, $res);
    }

    /**
     * 修改单位排序
     * @param orders 排序   json格式数据  里面2个参数  id 单位id   order 序号
     *
     * json 格式数据  [{"id":1,"order":1},{"id":2,"order":2},{"id":3,"order":3}]
     * 数组 格式数据  [['id'=>1 , 'order'=>1] , ['id'=>2 , 'order'=>2] , ['id'=>3 , 'order'=>3]]
     */
    public function orderChange()
    {
        if (!$this->validate->scene('order')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $orders = $this->request->orders;
        DB::beginTransaction();
        try {
            $this->model->orderChange($orders);
            DB::commit();
            return $this->returnApi(200, '修改成功', true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }

    /**
     * 默认与取消默认
     * @param id int 单位id
     * @param is_default int 发布   1 默认  2 取消默认
     */
    public function cancelAndDefault()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('cancel_and_default')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        DB::beginTransaction();
        try {
            if ($this->request->is_default == 1) {
                //取消所有的默认
                $act_id = $this->model->where('id', $this->request->id)->value('act_id');
                $this->model->where('act_id', $act_id)->update(['is_default' => 2, 'change_time' => date('Y-m-d H:i:s')]);
                $this->model->where('id', $this->request->id)->update(['is_default' => 1, 'change_time' => date('Y-m-d H:i:s')]);
            } else {
                //直接取消即可
                $this->model->where('id', $this->request->id)->update(['is_default' => 2, 'change_time' => date('Y-m-d H:i:s')]);
            }

            $is_default = $this->request->is_default == 1 ? '设置默认' : '取消默认';

            DB::commit();
            return $this->returnApi(200, $is_default . '成功');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }

    /**
     * 下载所有单位二维码
     * @param act_id int 活动id
     * @param area_id int 区域id
     * @param page int 当前页
     * @param limit int 分页大小
     * @param nature int 单位性质   1 图书馆  2 文化馆  3 博物馆
     * @param start_time datetime 创建时间范围搜索(开始)
     * @param end_time datetime 创建时间范围搜索(结束)
     * @param keywords string 搜索关键词(类型名称)
     */
    public function downloadUnitQr()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('list')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $page = 1;
        $limit = 99999;
        $start_time = $this->request->start_time;
        $end_time = $this->request->end_time;
        $nature = $this->request->nature;
        $keywords = $this->request->keywords;
        $act_id = $this->request->act_id;
        $area_id = $this->request->area_id;

        //判断是否是单位联盟活动
        $isAllowAddUnit = $this->model->isAllowAddUnit($this->request->act_id);
        if ($isAllowAddUnit !== true) {
            return $this->returnApi(202, $isAllowAddUnit);
        }

        $res = $this->model->lists(['name', 'qr_url'], $act_id, $keywords, $area_id, $nature, null, $start_time, $end_time, null, null, $limit);

        if ($res['total'] == 0 || !$res['data']) {
            return $this->returnApi(203, "暂无数据");
        }
        $zipFileDownloadObj = new ZipFileDownloadController();
        $path_arr = [];
        foreach ($res['data'] as $key => $val) {
            $path_arr[$key]['file_path'] = $val['qr_url'];
            $path_arr[$key]['file_name'] = $val['name'] . '.png';
        }
        $zip_path = $zipFileDownloadObj->addPackage($path_arr, null, '活动单位二维码下载-' . date('Y-m-d'), 10); //缓存时间长了，筛选数据还是之前的

        if (file_exists($zip_path)) {
            return response()->download($zip_path);
        }
        return $this->returnApi(202, "文件不存在");
    }

    /**
     * 从基础数据库中选择单位到活动里面
     * @param act_id int 活动id
     * @param unit_ids int 基础数据单位id  多个逗号拼接
     */
    public function selectBaseUnit()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('select_base_unit')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        DB::beginTransaction();
        try {
            $this->model->selectBaseUnit($this->request->act_id, $this->request->unit_ids);
            DB::commit();
            return $this->returnApi(200, '操作成功', true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }
}
